package com.enterprise.web;

import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.assg2.dao.*;
import com.movie.Book;
import com.movie.Cinema;
import com.movie.Movie;
import com.movie.Owner;
import com.movie.Show;
import com.movie.Viewer;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpSession;

/**
 * This is the command that will be used for logging in users.
 * If logon is successful, the command should place a list of contacts
 * in the request attriubutes.
 * @author  yunki
 */
public class BookCommand implements Command {

    /** Creates a new instance of LoginCommand */
    public BookCommand() {
    }

    public String execute(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //TODO: set the response content type to "text/html" here
        //TODO: You'll have to use getWriter() to output some HTML texts
        //TODO: close the output stream


        response.setContentType("text/html");// from response, set content type
        PrintWriter out = response.getWriter();// from response, get output writer

        HttpSession session = request.getSession(true);


        DaoMovie daomovie = new DaoMovie();
        DaoViewer daoviewer = new DaoViewer();
        DaoCinema daocinema = new DaoCinema();
        DaoShow daoshow = new DaoShow();



        //return "//header.html").include(request, response);


        if (request.getParameter("movieid") != null) {

            int movieid = Integer.parseInt(request.getParameter("movieid"));
            Movie m = (Movie) daomovie.findById(movieid);


            if (request.getParameter("cinemaid") != null && request.getParameter("calendarField") != null) {


                int cinema = Integer.parseInt(request.getParameter("cinemaid"));
                Cinema c = (Cinema) daocinema.findById(cinema);

                List<Show> listshows = new ArrayList<Show>();
                listshows = daoshow.findByMovieAndCinema(m, c);
                Date exp = TransformToDate(request.getParameter("calendarField"));
                Collections.sort(listshows);

                Calendar today = Calendar.getInstance();
                today.add(Calendar.DATE, -1);

                if (exp.before(m.getUntil()) && exp.after(m.getRelaseDate()) && exp.after(new java.util.Date(today.getTimeInMillis()))) {
                    request.setAttribute("movie", m);
                    request.setAttribute("listshows", listshows);
                    request.setAttribute("exp", exp);
                    return "/book.jsp";
                } else {
                    request.setAttribute("message", "Movie not available at this Date:<a href='javascript:history.go(-1)'>Go to Back</a>");
                    return "message";
                }
            } else {

                List<Cinema> listcinemas = new ArrayList<Cinema>();
                listcinemas = daocinema.findByMovie(m);

                if (listcinemas != null) {
                    Collections.sort(listcinemas);
                    request.setAttribute("movie", m);
                    request.setAttribute("listcinemas", listcinemas);
                    return "/bookdate.jsp";
                } else {
                    request.setAttribute("message", "Movie not available:<a href='javascript:history.go(-1)'>Go to Back</a>");
                    return "message";
                }
            }

        } else if (request.getParameter("idshow") != null) {

            if (request.getParameter("CardNumber") == null) {

                int idshow = Integer.parseInt(request.getParameter("idshow"));
                int numseats = Integer.parseInt(request.getParameter("numseatshow" + idshow));
                long datelong = Long.parseLong(request.getParameter("datebook" + idshow));
                Date datebook = new Date(datelong);

                request.setAttribute("idshow", idshow);
                request.setAttribute("numseats", numseats);
                request.setAttribute("datebook", datelong);

                return "/creditcard.jsp";
            } else {

                int idshow = Integer.parseInt(request.getParameter("idshow"));
                int numseats = Integer.parseInt(request.getParameter("numseats"));
                long datelong = Long.parseLong(request.getParameter("datebook"));
                Date datebook = new Date(datelong);


                DaoBook daobook = new DaoBook();
                Show s = (Show) daoshow.findById(idshow);

                Object user = (Object) session.getAttribute("user");

                if ((user != null) && (user instanceof Viewer)) {

                    Viewer v = (Viewer) daoviewer.findById(2);
                    Book b = new Book(s.getIdshow(), v.getIdviewer(), numseats, datebook);

                    v.getBooks().add(b);
                    s.getBooks().add(b);
                    b.setShow(s);
                    b.setViewer(v);

                    daobook.save(b);
                    request.setAttribute("message", "Booking Succesfull");
                    return "message";
                } else {
                    return "login";
                }

            }

        }

        request.setAttribute("message", "Problem here");
        return "message";
    }

    protected Object User(String user, String password) {
        DaoOwner daoowner = new DaoOwner();
        Owner owner = daoowner.findByUsername(user);

        if (owner != null) {
            if (owner.getPassword().matches(password)) {
                return owner; // trust everyone
            }
        }

        DaoViewer daoviewer = new DaoViewer();
        Viewer viewer = (Viewer) daoviewer.findBy("username", user);

        if (viewer != null) {
            if (viewer.getPassword().matches(password)) {
                return viewer;
            }
        }
        return null;
    }

    protected Date TransformToDate(String str_date) {
        try {
            DateFormat dfm = new SimpleDateFormat("MM-dd-yyyy");
            return dfm.parse(str_date);
        } catch (ParseException e) {
            System.out.println("Exception :" + e);
        }
        return null;
    }
}
